//
//  SearchNewsViewController.swift
//  weile
//
//  Created by LKM on 16/10/28.
//  Copyright © 2016年 LKM. All rights reserved.
//

import UIKit

class SearchNewsViewController: BaseViewController ,UITableViewDelegate,UITableViewDataSource ,ISearchAble{

    
    @IBOutlet weak var tableview: UITableView!
    
    var mListFooterLoadView :ListFooterLoadView!
    var refreshControl:UIRefreshControl!
//    var data:[SearchNewTo]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        mListFooterLoadView = ListFooterLoadView.createView();
        self.tableview.tableFooterView=mListFooterLoadView;
        
        self.tableview.register(UINib(nibName:"SearchNewsItem", bundle: nil), forCellReuseIdentifier: "ArticlesItem")
        
        //tableview参数设置
        tableview.rowHeight = 76.7//8+60+8+0.7
        tableview.separatorStyle = .none
        tableview.contentInset = UIEdgeInsetsMake(0, 0, MainTabBarHeight, 0)
        tableview.scrollIndicatorInsets = tableview.contentInset
        tableview.delegate=self;
        tableview.dataSource = self;
        //tableview参数设置  end
        
        // 添加刷新控件
        refreshControl = UIRefreshControl()
        //        refreshControl.attributedTitle = NSAttributedString(string: "松开后自动刷新")
        tableview.addSubview(refreshControl)
        refreshControl.addTarget(self, action: #selector(loadData(_:)), for: .valueChanged)
        // 添加刷新控件 end
        
//        if loadData(false){
//            refreshControl.beginRefreshing()
//        }
        
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    
    var keyWord:String="";
    
    func searchForKeyWord(keyWord: String, isForceRefresh: Bool) {
        if(self.keyWord != keyWord){
            self.keyWord = keyWord;
            forceRefresh()
        }else if isForceRefresh{
            forceRefresh()
        }
    }

    
    
    
    var listData: [SearchNewTo] = Array();//
    var curPage = 1;//第一开始
    var isLoadIng = false;//是否加载中
    var isLoadAppending = false;//是否加载更多数据
    var hasMoreData=true;//是否有更多数据
    
    @discardableResult
    func loadData(_ isLoadAppend :Bool) -> Bool{
        if isLoadIng {
            return isLoadAppend == isLoadAppending;
        }
        self.isLoadAppending=isLoadAppend;
        isLoadIng=true
        
        if(isLoadAppend){
            mListFooterLoadView.setAppending()
        }else{
            mListFooterLoadView.setRefreing()
        }
        
        let taskSerialNumber=Api.getSearchNew(preTaskSerialNumber: nil,page: isLoadAppend ? (curPage + 1) : 1, keyWord: keyWord){ (re:ResponEntity) in
            self.isLoadIng=false;
            if(re.isSuccess()){
                let data:[SearchNewTo]? = re.data as? [SearchNewTo];
                
                //数据是那些----
                var hasListData = !(CollectionHelp.isEmpty(  data )) //!(self.data?.prolist == nil);
                if(self.isLoadAppending){
                    self.curPage += hasListData ? 1 : 0;
                }else{
                    self.listData.removeAll();
                    self.curPage = 1;
                }
                self.listData +=  data ?? Array();
                
                self.hasMoreData = hasListData
                if(self.hasMoreData){//这个是针对这个搜索，后台没做分页的情况
                    //打于等于20就是有下一页
                    self.hasMoreData = CollectionHelp.size(data) >= LKMAPIListPageSize;
                }

                //没有更多数据了
                self.mListFooterLoadView.setNone(hasNextPage: hasListData)
                //数据是那些----end
                
                self.tableview.reloadData()
            }else{
                ViewHelp.showTipsView(containView: self.view, tips: re.msg);
            }
            self.refreshControl.endRefreshing()
        }
        curLoadTaskSerialNumber = taskSerialNumber
        taskAlls.append(taskSerialNumber);
        
        return true;
    }
    func forceRefresh(){
        isLoadIng=false;
        if let ts = curLoadTaskSerialNumber{
            Api.destroyTask(taskSerialNumbers: [ts])
        }
        
        loadData(false);
    }
    
    var curLoadTaskSerialNumber:Int?;
    var taskAlls = [Int]();
    deinit {
        //界面退出肯定就不登陆咯
        Api.destroyTask(taskSerialNumbers: taskAlls);
    }
    
    
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    // MARK: - UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listData.count
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let homeCell = tableView.dequeueReusableCell(withIdentifier: "ArticlesItem") as! SearchNewsItem
        homeCell.selectionStyle = .default
        homeCell.mSearchNewTo = self.listData[(indexPath as NSIndexPath).row]
        
        let count:Int=self.tableView( tableView, numberOfRowsInSection:1);
        if(indexPath.row+1>=count){
            //加载更多数据
            if hasMoreData{
                //一般到显示倒数第二个就会去加载
                loadData(true);
            }
            
        }
        
        
        return homeCell
    }
    // MARK: - UITableViewDelegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let o = self.listData[(indexPath as NSIndexPath).row]
        LKMLog("====\(navigationController!,o.id)")
        
        ActivityRequest.goArticleDetailController(navigationController!,o.id ?? "");
    }
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */

}

import Foundation
import SwiftyJSON

//lkm
class SearchNewTo: NSObject {
    
    var id: String?;//"124"
    var title: String?;//"轻钢别墅10"
    var title2: String?;//"VA224"
    var ImgUrl: String?;//""
    var kws: String?;//""
    var kindid: Int?;//"2"
    
    //dict["data"].dictionaryObject  dict是JSON
    init?(jsons: [String: JSON]?) {
        super.init()
        if(jsons == nil){
            return nil
        }
        
        if let dict = jsons{
        
        self.id = dict["id"]?.string;//"124"
        self.title = dict["title"]?.string;//"轻钢别墅10"
        self.title2 = dict["title2"]?.string;//"VA224"
        self.ImgUrl = dict["ImgUrl"]?.string;//""
        self.kws = dict["kws"]?.string;//""
        self.kindid = dict["kindid"]?.int;//"2"
    }
    }
    
    
    //initToList( json:JSON(dict["huxing"] ) )  把JSON过的Any转为JSON
    //一定要是JSON要是 [Any] 的话 会装换失败，最后我还是选用这个JSON
    class func initToList(json: JSON)->[SearchNewTo?]{
        if let items = json.array {
            var results = [SearchNewTo?]()
            for item in items {
                let result = SearchNewTo(jsons: item.dictionary )
                //                if(result != nil){//空还加个屁啊  json为“[]” 时 这是不会为空的。除非直接来了个nil
                //                    results.append(result!)
                //                }
                results.append(result)
            }
            return results;
        }
        return [SearchNewTo?]()
    }
    
    //initToList( json:JSON(dict["huxing"] ) )  把JSON过的Any转为JSON
    //一定要是JSON要是 [Any] 的话 会装换失败，最后我还是选用这个JSON
    class func initToMap(json: JSON)->Dictionary<String,SearchNewTo>{
        if let items = json.dictionary {
            var results = Dictionary<String,SearchNewTo>()//取值的时候本身就是可选类型啊,所以这里不用跟数组一样弄可选类型
            for (key, value)  in items {
                let result = SearchNewTo(jsons: value.dictionary )
                results[key] = result
            }
            return results;
        }
        return Dictionary<String,SearchNewTo>()
    }
    
    
    
    
}

